<template>
  <div id="details">
    <detail-nav-bar @titleClick="titleClick"></detail-nav-bar>
    <my-content :scrollTop="scrollTop">
      <details-content
        :position="position"
        :goodsId="goodsId"
        @position-change="positionChange"
      ></details-content>
      <my-action-bar
        @onClickCart="onClickCart"
        :goodsId="goodsId"
      ></my-action-bar>
    </my-content>
  </div>
</template>

<script>
import DetailNavBar from "@/views/detail/DetailNavBar.vue";
import MyContent from "@/components/common/content/Content.vue";
import DetailsContent from "@/components/content/details/DetailsContent.vue";
import MyActionBar from "../../components/common/actionbar/MyActionBar.vue";

export default {
  name: "Details",
  components: {
    DetailNavBar,
    DetailsContent,
    MyContent,
    MyActionBar,
  },
  data() {
    return {
      goodsId: "",
      position: "",
      scrollTop: 0,
    };
  },
  created() {
    this.goodsId = this.$route.query.goodsId;
  },
  methods: {
    titleClick(index) {
      switch (index) {
        case 0:
          this.position = "detail-banner";
          break;
        case 1:
          this.position = "detail-comment";
          break;
        case 2:
          this.position = "detail-param";
          break;
        case 3:
          this.position = "detail-commend";
          break;
        default:
          break;
      }
    },
    onClickCart(goodCart) {
      let currentUser = JSON.parse(sessionStorage.getItem("currentUser"));

      //判断商品存在否
      let goodById = currentUser.cartList.filter(
        (item) => item.goodsId === goodCart.goodsId
      );
      if (goodById.length != 0) {
        //如果存在，找出来并将其num++
        for (let i = 0; i < currentUser.cartList.length; i++) {
          if (currentUser.cartList[i].goodsId === goodById[0].goodsId) {
            currentUser.cartList[i].num++;
            break;
          }
        }
      } else {
        currentUser.cartList.push(goodCart);
      }
      sessionStorage.setItem("currentUser", JSON.stringify(currentUser));
      console.log("添加购物车成功");
    },
    positionChange(target) {
      this.scrollTop = target;
    },
  },
};
</script>

<style scoped>
#details {
  overflow: hidden;
}
</style>
